<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 具体页面结构 -->
      <pageTools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hExportExcel">导出excel</el-button>
          <el-button v-allow="'add_employees'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </pageTools>

      <el-card style="margin-top: 10px;">
        <el-table :data="EmployeeList" border>
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmployment(row.formOfEmployment) || '未知' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push('/detail?id=' + row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :page-size="size"
            :page-sizes="[2,5,8,10]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>

      <!-- 实现员工新增的弹层 -->
      <el-dialog
        title="新增员工"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
      >
        <empDialog
          v-if="showDialog"
          @close="showDialog = false"
          @success="hSuccess"
        />
      </el-dialog>

      <!-- 实现分配角色的弹层 -->
      <el-dialog
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialogRole"
      >
        <assignRole
          v-if="showDialogRole"
          :cur-id="curId"
          @close="showDialogRole = false"
          @success="roleSuccess"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import empDialog from '@/views/employees/empDialog.vue'
import { delEmployee, getEmployeeList } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import assignRole from '@/views/employees/assignRole.vue'

/*  // forEach方法
const hireType = {}
EmployeeEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
console.log('聘用形式', hireType) */

// new Array().reduce()
const hireType = EmployeeEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})

export default {
  name: 'Employees',
  components: { empDialog, assignRole },
  data() {
    return {
      page: 1, // 页码
      size: 5, // 每页条数
      EmployeeList: [],
      total: 0,
      showDialog: false, // 弹层的显示/隐藏
      showDialogRole: false, // 控制分配角色的弹层 (显示/隐藏)
      curId: ''
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    roleSuccess() {
      // 关闭弹层并且刷新页面
      this.showDialogRole = false
      this.loadEmployeeList()
    },
    hAssignRole(id) {
      console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.curId = id
    },
    hSuccess() {
      this.showDialog = false
      // 添加成功，进入最后一页看数据
      this.total++
      // 最后一页
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeeList()
    },
    // 删除员工数据
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('删除员工成功', res)
        this.$message.success(res.message)
        // 优化删除操作
        if (this.EmployeeList.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployeeList()
        // 保存数据
      } catch (error) {
        console.log(error)
      }
    },
    // 确认删除
    hDel(id) {
      console.log(id)
      this.$confirm('此操作将永久删除员工，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认
        this.doDel(id)
      }).catch(() => {

      })
    },
    // 每页几条
    hSizeChange(val) {
      // 1. 更新每页的条数
      this.size = val
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 会自动接收当前点击的页码
    hCurrentChange(val) {
      // 1. 更新页码
      this.page = val
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 聘用形式
    formOfEmployment(id) {
      return hireType[id]
    },
    // 获取列表
    async loadEmployeeList() {
      try {
        const { data: res } = await getEmployeeList({ page: this.page, size: this.size })
        console.log('获取员工列表成功', res)
        this.EmployeeList = res.rows
        this.total = res.total
      } catch (error) {
        console.log(error)
      }
    },

    // 英文转中文
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = hireType[key] // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })

      return { header, data }
    },

    // 导入excel
    hExportExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发ajax请求，获取数据
        const { data: res } = await getEmployeeList(this.page, this.size)
        const list = res.rows
        console.log('从后端获取的数据', list)

        const { header, data } = this.formatData(list)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    }

    /*
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false

        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header: ['姓名', '工资'], // 表头 必填
          data: [
            ['刘备', 100],
            ['关羽', 500]
          ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    }*/
  }
}
</script>

